// 安装第三方库 oliver/U8g2
// 安装第三方库esphome/ESPAsyncWebServer-esphome
// 安装第三方库Fabrice Weinberg/NTPClient
#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
#include "image.cpp"
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <LittleFS.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

#define PIN_SCL 5 // D1
#define PIN_SDA 4 // D2

AsyncWebServer server(80);

U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /*reset=*/U8X8_PIN_NONE, /*clock=*/PIN_SCL, /*data=*/PIN_SDA);

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com", 8 * 3600, 60000); // 60*1000,每分钟

const char *ssid = "我是wifi";
const char *password = "19900625";
const char *PARAM_MESSAGE = "message";

int emojiState = 0;
int prevEmojiState = 0;

// 首页html页面
void webroot(AsyncWebServerRequest *request)
{
    Serial.println("开始判断首页文件是否存在");
    // 检查SPIFFS文件系统中是否存在index.html文件
    if (LittleFS.exists("/index.html"))
    {
        fs::File file = LittleFS.open("/index.html", "r");
        { // 打开index.html
            if (file)
            {
                size_t fileSize = file.size(); // 获取文件大小
                String fileContent;

                // 逐字节读取文件内容
                while (file.available())
                {
                    fileContent += (char)file.read();
                }
                file.close(); // 关闭文件

                // 返回HTML内容
                Serial.println(fileContent);
                request->send(200, "text/html", fileContent);
                return;
            }
        }
    }
    // 如果文件不存在，返回404错误
    request->send(404, "text/plain", "Not found");
}

// 其他网址页面
void notFound(AsyncWebServerRequest *request)
{
    request->send(404, "text/plain", "Not found");
}

void setup()
{
    Serial.begin(9600);

    LittleFS.begin();    // 启动LittleFS
    WiFi.mode(WIFI_STA); // wifi连接
    WiFi.begin(ssid, password);
    if (WiFi.waitForConnectResult() != WL_CONNECTED)
    {
        Serial.printf("WiFi Failed!\n");
        return;
    }

    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP()); // 返回IP

    server.on("/", HTTP_GET, webroot); // 当局域网访问首页显示
    server.on("/bird", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        u8g2.clear();
        emojiState = 0;
        request->send(200, "text/plain", "Front Function Started"); }); // emojiState=0，默认显示
    server.on("/we", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        emojiState = 1;
        request->send(200, "text/plain", "Front Function Started"); }); // emojiState=1
    server.on("/apple", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        emojiState = 2;
        request->send(200, "text/plain", "Front Function Started"); }); // emojiState=2
    server.on("/huawei", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        emojiState = 3;
        request->send(200, "text/plain", "Front Function Started"); }); // emojiState=3
    server.on("/sketch", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        emojiState = 4;
        request->send(200, "text/plain", "Front Function Started"); }); // emojiState=4

    server.on("/time", HTTP_GET, [](AsyncWebServerRequest *request)
              {
        emojiState = 8;
        request->send(200, "text/plain", "Front Function Started"); });              // emojiState=4
    server.onNotFound(notFound); // 当局域网访问其他网址显示
    server.begin();

    timeClient.begin();
    timeClient.setTimeOffset(28800); // 8*3600   北京时间，东八区

    u8g2.begin();
    u8g2.setDisplayRotation(U8G2_R2);
    u8g2.firstPage();
}

void loop()
{
    if (emojiState != prevEmojiState)
    {
        u8g2.clearDisplay();
        prevEmojiState = emojiState;
    }
    switch (emojiState)
    {
    case 0:
        do
        {
            u8g2.setFont(u8g2_font_ncenB08_tr);
            u8g2.drawXBMP(0, 0, 128, 64, bird);
        } while (u8g2.nextPage());
        delay(100);
        break;

    case 1:
        do
        {
            u8g2.setFont(u8g2_font_ncenB08_tr);
            u8g2.drawXBMP(0, 0, 128, 64, we);
        } while (u8g2.nextPage());
        delay(100);
        break;
    case 2:
        do
        {
            u8g2.setFont(u8g2_font_ncenB08_tr);
            u8g2.drawXBMP(0, 0, 128, 64, apple);
        } while (u8g2.nextPage());
        delay(100);
        break;
    case 3:
        do
        {
            u8g2.setFont(u8g2_font_ncenB08_tr);
            u8g2.drawXBMP(0, 0, 128, 64, huawei);
        } while (u8g2.nextPage());
        delay(100);
        break;
    case 4:
        do
        {
            u8g2.setFont(u8g2_font_ncenB08_tr);
            u8g2.drawXBMP(0, 0, 128, 64, sketch);
        } while (u8g2.nextPage());
        delay(100);
        break;

    case 8:
        if (WiFi.status() != WL_CONNECTED)
        {
            do
            {
                u8g2.setFont(u8g2_font_ncenB08_tr);
                u8g2.drawXBMP(0, 0, 64, 64, wifiimage);
                u8g2.drawStr(64, 20, "IP:");
                IPAddress ip = WiFi.localIP();
                char ipStr[16];
                sprintf(ipStr, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
                u8g2.drawStr(64, 40, ipStr);
                u8g2.drawStr(64, 60, "Need NET");
            } while (u8g2.nextPage());
        }
        else
        {
            do
            {
                // 更新时间
                u8g2.setFont(u8g2_font_ncenB08_tr);
                timeClient.update();
                u8g2.drawXBMP(0, 0, 64, 64, clockimage);
                // 获取当前时间
                int currenHour = timeClient.getHours();
                int currenMinute = timeClient.getMinutes();
                String timeToDisplay = String(currenHour) + ":" + String(currenMinute);
                u8g2.drawStr(64, 30, "TIME");
                u8g2.setCursor(64, 50);
                u8g2.print(timeToDisplay);
            } while (u8g2.nextPage());
        }

        delay(100);
        break;

    default:
        break;
    }
}